package net.wofly.sale.shoppingcart.service.impl;

import net.wofly.common.util.CommonStatus;
import net.wofly.common.util.Identities;
import net.wofly.framework.util.ResultCode;
import net.wofly.framework.util.ReturnBean;
import net.wofly.right.domain.User;
import net.wofly.right.domain.UserRole;
import net.wofly.right.service.IUserRoleService;
import net.wofly.right.service.IUserService;
import net.wofly.sale.commodity.domain.Commodity;
import net.wofly.sale.commodity.domain.CommodityChannel;
import net.wofly.sale.commodity.domain.OrderTypeChannelMapping;
import net.wofly.sale.commodity.domain.RoleDefaultOrderType;
import net.wofly.sale.commodity.service.IChannelCommodityTmlMappingService;
import net.wofly.sale.commodity.service.ICommodityChannelService;
import net.wofly.sale.commodity.service.ICommodityService;
import net.wofly.sale.commodity.service.ICommodityTmlService;
import net.wofly.sale.commodity.service.IOrderTypeChannelMappingService;
import net.wofly.sale.commodity.service.IRoleDefaultOrderTypeService;
import net.wofly.sale.order.domain.Order;
import net.wofly.sale.order.domain.OrderContent;
import net.wofly.sale.order.service.IRoleOrderTypeService;
import net.wofly.sale.order.service.ISaleOrderService;
import net.wofly.sale.order.util.OrderType;
import net.wofly.sale.order.util.PlaceOrderType;
import net.wofly.sale.shoppingcart.entity.CartList;
import net.wofly.sale.shoppingcart.entity.ShoppingCart;
import net.wofly.sale.shoppingcart.repository.ShoppingCartRepository;
import net.wofly.sale.shoppingcart.service.ICartListService;
import net.wofly.sale.shoppingcart.service.IShoppingCartService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/10/29.
 */
@Service("iShoppingCartService")
public class ShoppingCartServiceImpl implements IShoppingCartService {
    
    Logger logger = LoggerFactory.getLogger(ShoppingCartServiceImpl.class);
    
    @Autowired
    ShoppingCartRepository shoppingCartRepository;
    
    @Autowired
    ICartListService iCartListService;
    
    @Autowired
    ICommodityService iCommodityService;
    
    @Autowired
    IUserService iUserService;
    
    @Autowired
    IUserRoleService iUserRoleService;
    
    
    @Autowired
    ICommodityChannelService iCommodityChannelService;
    
    @Autowired
    ISaleOrderService iSaleOrderService;
    
    @Autowired
    IRoleOrderTypeService iRoleOrderTypeService;
    
    @Autowired
    private IOrderTypeChannelMappingService iOrderTypeChannelMappingService;
    @Autowired
    private ICommodityTmlService iCommodityTmlService;
    @Autowired
    private IChannelCommodityTmlMappingService iChannelCommodityTmlMappingService;
    
    @Autowired
    private IRoleDefaultOrderTypeService iRoleDefaultOrderTypeService;
    
    @Override
    public ReturnBean<String> addCommodityToCart(
            String userID, Integer shoppingCartType, String commodityID, Integer num) {
        Commodity commodity = iCommodityService.findOne(commodityID);
        if (commodity == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "商品不存在，添加购物车失败！");
        }
        
        ShoppingCart shoppingCart = shoppingCartRepository.findByShoppingCartIDAndShoppingCartType(userID,
                shoppingCartType);
        if (shoppingCart == null) {
            shoppingCart = new ShoppingCart(userID, shoppingCartType, System.currentTimeMillis());
            shoppingCartRepository.save(shoppingCart);
        }
        
        CartList cartList = iCartListService.findByShoppingCartIDAndCommodityID(userID, shoppingCartType, commodityID);
        if (cartList == null) {
            cartList = new CartList(Identities.uuid2(), shoppingCartType, System.currentTimeMillis(), num, userID,
                    commodity);
        } else {
            cartList.setNum(cartList.getNum() + num);
        }
        
        iCartListService.save(cartList);
        
        return new ReturnBean<>(ResultCode.SUCCESS, "添加商品到购物车成功！");
    }
    
    @Override
    public ReturnBean<String> changeCommodityNum(String cartListID, Integer num) {
        CartList cartList = iCartListService.findOne(cartListID);
        if (cartList == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "商品不存在，不能修改商品数量！");
        }
        
        cartList.setNum(num);
        iCartListService.save(cartList);
        return new ReturnBean<>(ResultCode.SUCCESS, "修改商品数量成功！");
    }
    
    @Override
    public ReturnBean<String> delCommodity(String cartListID) {
        iCartListService.delete(cartListID);
        return new ReturnBean<>(ResultCode.SUCCESS, "删除商品成功！");
    }
    
    @Override
    public ReturnBean<List<CartList>> getCartList(String userID, Integer shoppingCartType) {
        User user = iUserService.findOne(userID);
        if (user == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户不存在，不能获取购物车列表！");
        }
        
        List<UserRole> userRoles = iUserRoleService.findByUserID(userID);
        if (userRoles == null || userRoles.size() == 0) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户没有角色，不能获取购物车列表！");
        }
        
        String roleID = userRoles.get(0).getRoleID();
        String userChannel = roleID.substring(roleID.length() - 1);
        
        List<CartList> cartLists = iCartListService.findByShoppingCartID(userID, shoppingCartType);
        
        if (Integer.parseInt(roleID) < 200) {
            for (CartList cartList : cartLists) {
                Commodity commodity = cartList.getCommodity();
                cartList.setTotalAmount(commodity.getPrice() * cartList.getNum());
                
                CommodityChannel commodityChannel = new CommodityChannel() ;
                commodityChannel.setCommodityChannelPrise(commodity.getPrice());
                cartList.getCommodity().setCommodityChannel(commodityChannel);
            }
        } else {
            for (CartList cartList : cartLists) {
                Commodity commodity = cartList.getCommodity();
                CommodityChannel commodityChannel = iCommodityChannelService.findByCommodityIDAndChannel(
                        commodity.getCommodityID(), userChannel);
                cartList.getCommodity().setCommodityChannel(commodityChannel);
                if (commodityChannel != null) {
                    cartList.setTotalAmount(commodityChannel.getCommodityChannelPrise() * cartList.getNum());
                } else {
                    cartList.setTotalAmount(commodity.getPrice() * cartList.getNum());
                }
            }
        }
        
        return new ReturnBean<>(ResultCode.SUCCESS, "获取购物车商品成功！", cartLists);
    }
    
    @Override
    public ReturnBean<Order> commitCart(String userID, List<CartList> carts) throws CloneNotSupportedException {
        Order order = new Order();
        order.setBuyer(userID);
        
        User user = iUserService.findOne(userID);
        if (user == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户不存在，不能获取购物车列表！");
        }
        
        List<UserRole> userRoles = iUserRoleService.findByUserID(userID);
        if (userRoles == null || userRoles.size() == 0) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "用户没有角色，不能获取购物车列表！");
        }
        
        String roleID = userRoles.get(0).getRoleID();
        
        String userChannel;
        List<OrderContent> orderContentList = new ArrayList<>();
        if (Integer.valueOf(roleID) >= 200) {
            
            userChannel = roleID.substring(roleID.length() - 1);
            
            for (CartList cartList : carts) {
                if (cartList.getCommodity() == null || StringUtils.isBlank(cartList.getCommodity().getCommodityID())) {
                    return new ReturnBean<>(ResultCode.ERROR_SERVICE, "商品ID不能为空！");
                }
                Commodity commodity = iCommodityService.findOne(cartList.getCommodity().getCommodityID());
                if (commodity == null) {
                    return new ReturnBean<>(ResultCode.ERROR_SERVICE,
                            "商品(" + cartList.getCommodity().getCommodityID() + ")未找到！");
                }
                CommodityChannel commodityChannel = iCommodityChannelService.findByCommodityIDAndChannel(
                        commodity.getCommodityID(), userChannel);
                cartList.getCommodity().setCommodityChannel(commodityChannel);
                
                OrderContent orderContent = new OrderContent();
                orderContent.setCommodity(commodity);
                orderContent.setCommodityChannelID(commodityChannel.getCommodityChannelID());
                orderContent.setNum(cartList.getNum());
                
                orderContentList.add(orderContent);
            }
            
            Integer orderType;
            switch (Integer.valueOf(userChannel)) {
                case 1:
                    orderType = OrderType.会员订单.getValue();
                    break;
                case 2:
                    orderType = OrderType.团购订单.getValue();
                    break;
                case 3:
                    orderType = OrderType.流通订单.getValue();
                    break;
                case 4:
                    orderType = OrderType.酒店订单.getValue();
                    break;
                case 5:
                    orderType = OrderType.签单订单.getValue();
                    break;
                default:
                    orderType = OrderType.会员订单.getValue();
                    break;
            }
            
            order.setOrderType(orderType);
            order.setCustomerUserID(userID);
            order.setPlaceOrderType(PlaceOrderType.自助下单.getValue());
            order.setOrderContents(orderContentList);
            
            ReturnBean<Order> returnBean = iSaleOrderService.handleOrder(order);
            returnBean.setMsg("确认订单成功！");
            return returnBean;
        } else {
            order.setPlaceOrderType(PlaceOrderType.代客下单.getValue());
            
            //查找角色的默认订单类型
            RoleDefaultOrderType roleDefaultOrderType = iRoleDefaultOrderTypeService.findByRoleID(roleID);
            
            if (null == roleDefaultOrderType) {
                return new ReturnBean<>(ResultCode.ERROR_SERVICE, "未配置相关角色的默认订单类型，请联系管理员处理！");
            }
            //设置默认的订单类型
            order.setOrderType(Integer.valueOf(roleDefaultOrderType.getOrderType()));
            
            for (CartList cartList : carts) {
                if (cartList.getCommodity() == null || StringUtils.isBlank(cartList.getCommodity().getCommodityID())) {
                    return new ReturnBean<>(ResultCode.ERROR_SERVICE, "商品ID不能为空！");
                }
                Commodity commodity = iCommodityService.findOne(cartList.getCommodity().getCommodityID());
                if (commodity == null) {
                    return new ReturnBean<>(ResultCode.ERROR_SERVICE,
                            "商品(" + cartList.getCommodity().getCommodityID() + ")未找到！");
                }
                
                //查找订单类型和渠道的关系
                OrderTypeChannelMapping orderTypeChannelMapping = iOrderTypeChannelMappingService.findByOrderType(
                        order.getOrderType().toString());
                if (null == orderTypeChannelMapping) {
                    logger.info(">>> 未找到订单类型和渠道的关系配置数据...");
                }
                
                //查找商品渠道
                CommodityChannel commodityChannel = iCommodityChannelService.findByCommodityIDAndChannel(
                        commodity.getCommodityID(), orderTypeChannelMapping.getChannel());
                cartList.getCommodity().setCommodityChannel(commodityChannel);
                
                OrderContent orderContent = new OrderContent();
                orderContent.setCommodity(commodity);
                orderContent.setCommodityChannelID(commodityChannel.getCommodityChannelID());
                orderContent.setNum(cartList.getNum());
                
                orderContentList.add(orderContent);
            }
            order.setOrderContents(orderContentList);
        }
        ReturnBean<Order> returnBean = iSaleOrderService.handleOrder(order);
        if (ResultCode.SUCCESS.intValue() == returnBean.getCode().intValue()) {
            return new ReturnBean<>(ResultCode.SUCCESS, "确认订单成功", returnBean.getResult());
        } else {
            return new ReturnBean<>(returnBean.getCode(), returnBean.getMsg(), returnBean.getResult());
        }
    }
}
